import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
// import store from '../store'

console.log(process.env.NODE_ENV)
let socketUrl
if (process.env.NODE_ENV === 'development') {
  socketUrl = '//beta.tupu360.bj/ats/notification/stomp'
} else {
  socketUrl = '/ats/notification/stomp'
}

let socket = {}
let timer = null
let reconnectInterval = 0
let reconnectTimes = 0
let stompSuccessCallback = function () {
  reconnectInterval = 0
  reconnectTimes = 0
  // store.state.app.socketConnect = true
  socket.socketClient.debug('STOMP: connected')
}

let stompFailureCallback = function () {
  clearTimeout(timer)
  timer = setTimeout(socket.stompConnect, reconnectInterval * 1000)
  socket.socketClient.debug('STOMP: Reconnecting in ' + reconnectInterval + ' seconds')
  reconnectTimes++
  if (reconnectTimes > 10) {
    reconnectTimes = 10
  }
  reconnectInterval = Math.pow(2, reconnectTimes)
}

socket.stompConnect = function () {
  let sockJs = new SockJS(socketUrl)
  socket.socketClient = Stomp.over(sockJs, {
    debug: false
  })
  socket.socketClient.debug('STOMP: Attempting connection...')
  socket.socketClient.connect({}, stompSuccessCallback, stompFailureCallback)
}

console.log(`going to connect to ${socketUrl}`)

export default socket
